package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Constants;
import com.changgou.goods.dao.*;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private IdWorker idWorker;//注入雪花算法

    @Autowired
    private CategoryMapper categoryMapper;//分类

    @Autowired
    private BrandMapper brandMapper;//品牌

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Spu findById(String id){
        return  spuMapper.selectByPrimaryKey(id);
    }


    /**
     * 增加
     * @param spu
     */
    @Override
    public void add(Spu spu){
        spuMapper.insert(spu);
    }


    /**
     * 修改
     * @param spu
     */
    @Override
    public void update(Spu spu){
        spuMapper.updateByPrimaryKey(spu);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id){
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Spu>)spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Spu>)spuMapper.selectByExample(example);
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andEqualTo("id",searchMap.get("id"));
           	}
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                criteria.andEqualTo("sn",searchMap.get("sn"));
           	}
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                criteria.andLike("caption","%"+searchMap.get("caption")+"%");
           	}
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                criteria.andLike("image","%"+searchMap.get("image")+"%");
           	}
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                criteria.andLike("images","%"+searchMap.get("images")+"%");
           	}
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                criteria.andLike("saleService","%"+searchMap.get("saleService")+"%");
           	}
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                criteria.andLike("introduction","%"+searchMap.get("introduction")+"%");
           	}
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                criteria.andLike("specItems","%"+searchMap.get("specItems")+"%");
           	}
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                criteria.andLike("paraItems","%"+searchMap.get("paraItems")+"%");
           	}
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                criteria.andEqualTo("isMarketable",searchMap.get("isMarketable"));
           	}
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
           	}
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andEqualTo("isDelete",searchMap.get("isDelete"));
           	}
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                criteria.andEqualTo("status",searchMap.get("status"));
           	}

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                criteria.andEqualTo("brandId",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                criteria.andEqualTo("category1Id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                criteria.andEqualTo("category2Id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                criteria.andEqualTo("category3Id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                criteria.andEqualTo("templateId",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                criteria.andEqualTo("freightId",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                criteria.andEqualTo("saleNum",searchMap.get("saleNum"));
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                criteria.andEqualTo("commentNum",searchMap.get("commentNum"));
            }

        }
        return example;
    }

    /**
     * 新增商品
     * @param goods
     */
    @Transactional
    @Override
    public void addGoods(Goods goods) {
        //1 保存spu数据
        goods.getSpu().setId(String.valueOf(idWorker.nextId()));//雪花算法生成主键id
        spuMapper.insertSelective(goods.getSpu());

        //2 保存sku列表数据
        saveSkuList(goods);
    }


    /**
     * 保存skuList列表   抽取公共方法(ctrl+Alt+M) 提高代码复用性 新增和更新都有用到更新skuList的功能 所以对该功能进行抽取
     * @param goods
     */
    private void saveSkuList(Goods goods) {
        Spu spu = goods.getSpu();
        String spuId = spu.getId();//获取spuid
        Integer category3Id = spu.getCategory3Id();//获取category三级id
        //根据分类id查询分类
        Category category = categoryMapper.selectByPrimaryKey(category3Id);

        //根据品牌id查询品牌
        Integer brandId = spu.getBrandId();
        Brand brand = brandMapper.selectByPrimaryKey(brandId);

        //处理分类与品牌的关联关系
        CategoryBrand categoryBrand = new CategoryBrand();
        categoryBrand.setBrandId(brandId);
        categoryBrand.setCategoryId(category3Id);
        int count = categoryBrandMapper.selectCount(categoryBrand);
        if (count <= 0) {
            categoryBrandMapper.insertSelective(categoryBrand);
        }

        //在此处理skuList，sku没有传过来的值
        //id name create_time update_time spu_id category_id category_name brand_name
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {
            sku.setId(String.valueOf(idWorker.nextId()));//雪花算法生成sku主键id

            //处理空字符串 json数据
            if (StringUtils.isEmpty(sku.getSpec())) {
                sku.setSpec("{}");
            }

            //spec的值格式如：{‘颜色’：‘紫色’，‘尺码’：‘250度’}
            String name = spu.getName();
            Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            for (String key : specMap.keySet()) {
                String value = specMap.get(key);
                name += " " + value;
            }
            sku.setName(name);//名称组成规则：spu名称+ 规格1 + 规格2 + 规格3...
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
            sku.setSpuId(spuId);
            if (category != null) {
                sku.setCategoryId(category3Id);//三级分类
                sku.setCategoryName(category.getName());//三级分类名称
            }
            if (brand != null) {
                sku.setBrandName(brand.getName());//品牌名
            }

            skuMapper.insertSelective(sku);

        }
    }

    /**
     * 查询商品
     * @param spuId
     * @return
     */
    @Override
    public Goods findBysouId(String spuId) {
        //通过spuID查询spu
        Spu  spu=spuMapper.selectByPrimaryKey(spuId);

        //通过spuId查询sku列表
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);

        //封装goods
        Goods goods = new Goods();
        goods.setSpu(spu);
        goods.setSkuList(skuList);

        return goods;
    }

    /**
     * 更新商品
     * @param goods
     */
    @Transactional
    @Override
    public void updateGoods(Goods goods) {
        //更新spu表
        spuMapper.updateByPrimaryKeySelective(goods.getSpu());

        //通过spuId删除sku数据
        Sku sku = new Sku();
        sku.setSpuId(goods.getSpu().getId());
        skuMapper.delete(sku);

        //新增skuList数据
        saveSkuList(goods);
    }

    /**
     * 审核商品
     * @param spuId
     */
    @Override
    public void auditGoods(String spuId) {
        //1 判断商品是否存在
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu==null){
            throw new RuntimeException("商品不存在");
        }

        //2 判断商品是否审核通过
        if("1".equals(spu.getStatus())){
            throw new RuntimeException("商品已审核过");
        }

        //3 执行审核状态更新
        Spu spuUpdate = new Spu();//重新new一个的目的是为了减短update语句，减少sql查询的时间和压力 见下
        spuUpdate.setId(spuId);
        spuUpdate.setStatus("1");
        spuMapper.updateByPrimaryKeySelective(spuUpdate);//update Status="1" where spuId

        /* 不建议这样写 这样写会将 spu所有字段重新查询更新
        spu.setStatus("1");
        spuMapper.updateByPrimaryKeySelective(spu);*/
    }


    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void upGoods(String spuId) {
        //1 判断商品是否存在
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu==null){
            throw new RuntimeException("该商品不存咋");
        }
        //2 判断商品是否审核通过
        if ("0".equals(spu.getStatus())){
            throw new RuntimeException("该商品暂未通过审核，不能上架");
        }
        //3 判断商品是否上架过
        if ("1".equals(spu.getIsMarketable())){
            throw new RuntimeException("该商品已上架，不能重复上架");
        }
        //4 执行商品上架状态更新
        Spu spuIsMarket = new Spu();
        spuIsMarket.setId(spuId);
        spuIsMarket.setIsMarketable("1");
        spuMapper.updateByPrimaryKeySelective(spuIsMarket);

        //5 将spuId存放到rabbitMq中
        rabbitTemplate.convertAndSend(Constants.GOODS_UP_EXCHANGE, null, spuId);

    }

    /**
     * 商品下架
     * @param spuId
     */
    @Override
    public void downGoods(String spuId) {
        //1 判断商品是否存在
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu==null){
            throw new RuntimeException("商品不存在");
        }
        //2 判断商品已下架过
        if ("0".equals(spu.getIsMarketable())){
            throw new RuntimeException("商品已处于下架状态，不能下架");
        }
        //3 执行商品下架状态更新
        Spu spuUpdate = new Spu();
        spuUpdate.setId(spuId);
        spuUpdate.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spuUpdate);

        //4 将spuId存入rabbitMq中
        rabbitTemplate.convertAndSend(Constants.GOODS_DOWN_EXCHANGE, null, spuId);

    }

    /**
     * 逻辑删除商品
     * @param spuId
     */
    @Override
    public void deleteLogic(String spuId) {
        //1 判断商品是否存在
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu==null){
            throw new RuntimeException("该商品不存在");
        }
        //2 判断商品是否下架
        if("1".equals(spu.getIsMarketable())){
            throw new RuntimeException("该商品未下架，不能删除");
        }
        //3 判断商品是否已删除
        if ("1".equals(spu.getIsDelete())){
            throw new RuntimeException("该商品处于删除状态，不能重复删除");
        }
        //4 执行商品逻辑删除操作
        Spu spuUpdate = new Spu();
        spuUpdate.setId(spuId);
        spuUpdate.setIsDelete("1");
        spuMapper.updateByPrimaryKeySelective(spuUpdate);
    }

    /**
     * 恢复逻辑删除商品
     * @param spuId
     */
    @Override
    public void restore(String spuId) {
        //1 判断商品是否存在
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu==null){
            throw new RuntimeException("该商品不存在");
        }
        //2 判断商品是否已逻辑删除
        if ("0".equals(spu.getIsDelete())){
            //未删除状态
            throw new RuntimeException("该商品未处于删除状态，无需恢复");
        }

        //3 已删除状态 执行恢复商品操作
        Spu spuUpdate = new Spu();
        spuUpdate.setId(spuId);
        spuUpdate.setIsDelete("0");
        spuMapper.updateByPrimaryKeySelective(spuUpdate);
    }

    /**
     * 物理删除商品
     * @param spuId
     */
    @Override
    public void deleteGoods(String spuId) {
        //判断商品是否存在
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu==null){
            throw new RuntimeException("该商品不存在");
        }
        //删除spu
        spuMapper.deleteByPrimaryKey(spuId);
        //删除skuList
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        skuMapper.delete(sku);
    }
}
